package com.terrace.db.system.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.terrace.db.constant.DBType;
import com.terrace.db.system.dao.RoleDao;
import com.terrace.db.system.dao.RolePermissionDao;
import com.terrace.db.system.dao.UserRoleDao;
import com.terrace.db.system.mapper.entity.Role;
import com.terrace.db.system.mapper.entity.UserRole;
import com.terrace.db.system.service.RoleService;
import com.terrace.core.mybatis.entity.Pagination;
import com.terrace.core.mybatis.plugin.pagination.PaginationHelper;
import com.terrace.core.utils.ApplicationContextUtil;
import com.terrace.core.spring.datasource.annotation.DataSource;

@Service
@Transactional
@DataSource(name = DBType.ADMIN)
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private RoleDao roleDao;

	@Override
	public int saveRoleSelective(Role role) {
		return roleDao.saveRoleSelective(role);
	}

	@Override
	public int deleteRoleById(String roleId) {
		RolePermissionDao rolePermissionDao = ApplicationContextUtil.getContext().getBean(RolePermissionDao.class);
		rolePermissionDao.batchDeleteRolePermissionByRoleId(roleId, null);
		return roleDao.deleteByRoleId(roleId);
	}
	
	@Override
	public int deleteByUserAndRoleId(String userId, String roleId) {
		UserRoleDao userRoleDao = ApplicationContextUtil.getContext().getBean(UserRoleDao.class);
		return userRoleDao.deleteByUserAndRoleId(userId, roleId);
	}

	@Override
	public int updateByRoleIdSelective(Role role) {
		return roleDao.updateByRoleIdSelective(role);
	}
	
	@Override
	public Role selectByRoleId(String roleId) {
		return roleDao.selectByRoleId(roleId);
	}
	
	@Override
	public int roleGrantUser(UserRole userRole) {
		UserRoleDao userRoleDao = ApplicationContextUtil.getContext().getBean(UserRoleDao.class);
		return userRoleDao.saveUserRoleSelective(userRole);
	}
	
	@Override
	public List<Role> selectRoleByUserId(String userId) {
		return roleDao.selectRoleByUserId(userId);
	}

	@Override
	public Pagination<Role> selectRolesBySelective(Role role, Pagination<Role> pagination) {
		PaginationHelper.prepare(pagination);
		return PaginationHelper.execute(roleDao.selectRolesBySelective(role));
	}

}
